package com.jiawa.train.member.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import com.jiawa.train.common.exception.BusinessException;
import com.jiawa.train.common.exception.BusinessExceptionEnum;
import com.jiawa.train.common.properties.JwtProperties;
import com.jiawa.train.common.util.JWTUtil;
import com.jiawa.train.common.util.SnowUtil;
import com.jiawa.train.member.domain.Member;
import com.jiawa.train.member.domain.MemberExample;
import com.jiawa.train.member.mapper.MemberMapper;
import com.jiawa.train.member.req.MemberLoginReq;
import com.jiawa.train.member.req.MemberSendCodeReq;
import com.jiawa.train.member.resp.MemberLoginResp;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class MemberService {
    @Resource
    private MemberMapper memberMapper;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private JwtProperties jwtProperties;

    //注册功能和发送验证码的功能实现
    public String  sendCode(MemberSendCodeReq req) {
        //1.校验手机号是否已经注册
        String mobile = req.getMobile();
        List<Member> list = selectByMobile(mobile);
        //当数据库中没有该手机号时，进行创建插入的对象
        if(CollUtil.isEmpty(list)){
            log.info("手机号不存在，进行保存");
            Member member = new Member();
            member.setId(SnowUtil.getSnowflakeNextId());
            member.setMobile(mobile);
            memberMapper.insert(member);
        }
        //当数据库中已经有手机号后，进行生成code然后返回前端
        String code = RandomUtil.randomString(4);
        log.info("生成的验证码为：{}",code);
        //然后使用redis将手机号和code进行存放
        String key = "LOGIN_CODE:" + mobile;
        redisTemplate.opsForValue().set(key, code, 2, TimeUnit.MINUTES);
        String LOGIN_CODE = (String) redisTemplate.opsForValue().get(key);
        log.info("LOGIN_CODE的值为：",LOGIN_CODE);
        return code;
    }

    //抽取出来的方法，根据手机号查询会员信息
    private List<Member> selectByMobile(String mobile) {
        MemberExample memberExample = new MemberExample();
        memberExample.createCriteria().andMobileEqualTo(mobile);
        List<Member> list = memberMapper.selectByExample(memberExample);
        return list;
    }

    //登录功能实现
    public MemberLoginResp login(MemberLoginReq req) {
        //先进行校验验证码和手机号是否正确，如果正确则需要返回token
        String key = "LOGIN_CODE:" + req.getMobile();
        String code = (String) redisTemplate.opsForValue().get(key);
        //当redis中没有验证码，则返回错误信息
        if(code == null){
            throw new BusinessException(BusinessExceptionEnum.MEMBER_CODE_NULL);
        }
        //如果用户填写的验证码和redis中的验证码不一致，则返回错误信息
        if(!code.equals(req.getCode())){
            throw new BusinessException(BusinessExceptionEnum.MEMBER_CODE_ERROR);
        }
        //如果验证码一致则进行判断手机号是否一致,直接使用抽取出来的方法进行访问数据库
        List<Member> list= selectByMobile(req.getMobile());
        //如果数据库中没有该手机号，则返回错误信息
        if(CollUtil.isEmpty(list)){
            throw new BusinessException(BusinessExceptionEnum.MEMBER_MOBILE_NOT_EXIST);
        }
        //如果手机号一致，则使用JWT工具生成token然后进行返回
        //创建负荷，然后进行调用创建JWT
        Map<String,Object> claims = new HashMap<>();
        claims.put("id",list.get(0).getId());
        claims.put("mobile",list.get(0).getMobile());
        String token = JWTUtil.createJWT(jwtProperties.getAdminSecretKey(), jwtProperties.getAdminTtl(), claims);
        MemberLoginResp memberLoginResp = MemberLoginResp.builder()
                .id(list.get(0).getId())
                .mobile(list.get(0).getMobile())
                .token(token)
                .build();
        return memberLoginResp;
    }
}

